package com.example.project7.viewmodel;

import android.app.Application;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.example.project7.model.User;
import com.example.project7.repository.UserRepository;
import com.example.project7.utils.ApiResponse;

import java.util.List;

public class UserViewModel extends AndroidViewModel {
    private static final String TAG = "UserViewModel";
    
    private UserRepository userRepository;
    private MutableLiveData<UserState> userStateLiveData = new MutableLiveData<>();

    public UserViewModel(@NonNull Application application) {
        super(application);
        userRepository = new UserRepository(application.getApplicationContext());
    }

    public LiveData<UserState> getUserState() {
        return userStateLiveData;
    }

    /**
     * 加载用户列表
     *
     * @param page 页码
     */
    public void loadUsers(int page) {
        Log.d(TAG, "加载用户列表，页码: " + page);
        userStateLiveData.setValue(new UserState.Loading());
        
        new Thread(() -> {
            try {
                ApiResponse<List<User>> response = userRepository.getUsers(page);
                if (response.isSuccess()) {
                    List<User> users = response.getData();
                    if (users != null && !users.isEmpty()) {
                        // 加载成功，有数据
                        userStateLiveData.postValue(new UserState.Success(users));
                    } else {
                        // 加载成功，但无数据
                        userStateLiveData.postValue(new UserState.Empty());
                    }
                } else {
                    // 加载失败
                    userStateLiveData.postValue(new UserState.Error(response.getErrorMessage()));
                }
            } catch (Exception e) {
                Log.e(TAG, "加载用户列表时发生异常", e);
                userStateLiveData.postValue(new UserState.Error("加载失败: " + e.getMessage()));
            }
        }).start();
    }
}